package repository

import (
	"database/sql/driver"
	"encoding/json"
)

/**
CREATE TABLE `notification_message` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键',
  `msg_id` bigint NOT NULL DEFAULT '0' COMMENT '消息ID',
  `msg_content` json DEFAULT NULL COMMENT '消息内容',
  `msg_type` tinyint NOT NULL DEFAULT '0' COMMENT '消息类型',
  `is_delete` tinyint NOT NULL DEFAULT '0' COMMENT '是否删除：0-未删除，1-已删除',
  `create_time` bigint NOT NULL DEFAULT '0' COMMENT '创建时间',
  `update_time` bigint NOT NULL DEFAULT '0' COMMENT '更新时间',
  `create_user_id` bigint NOT NULL DEFAULT '0' COMMENT '创建人',
  `update_user_id` bigint NOT NULL DEFAULT '0' COMMENT '更新人',
  PRIMARY KEY (`id`),
  KEY `idx_msg_id` (`msg_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/

type MsgContent struct {
	Text string `json:"text"`
	Img  string `json:"img"`
}

func (c MsgContent) Value() (driver.Value, error) {
	b, err := json.Marshal(c)
	return string(b), err
}

func (c *MsgContent) Scan(input interface{}) error {
	return json.Unmarshal(input.([]byte), c)
}

type NotificationMessage struct {
	ID           int64      `gorm:"column:id;primaryKey"`
	MsgId        int64      `gorm:"column:msg_id"`
	MsgContent   MsgContent `gorm:"TYPE:json;column:msg_content"`
	MsgType      int8       `gorm:"column:msg_type"`
	IsDelete     int8       `gorm:"column:is_delete"`
	CreateTime   int64      `gorm:"column:create_time"`
	UpdateTime   int64      `gorm:"column:update_time"`
	CreateUserId int64      `gorm:"column:create_user_id"`
	UpdateUserId int64      `gorm:"column:update_user_id"`
}

func InsertNotificationMessage(msg NotificationMessage) (NotificationMessage, error) {
	//必须使用指针的方式
	t := db.Create(&msg)
	return msg, t.Error
}

func SelectOneNotificationMessageByMsgId(msgId int64) (NotificationMessage, error) {
	var msg NotificationMessage
	tx := db.Where("msg_id = ?", msgId).First(&msg)
	return msg, tx.Error
}
